/*
  Complete Getting Started Guide: https://RandomNerdTutorials.com/esp32-bluetooth-low-energy-ble-arduino-ide/
  Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp
  Ported to Arduino ESP32 by Evandro Copercini
*/

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <Arduino.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

//然后，您需要为服务和特性定义一个 UUID
//服务有很多特性，特性包含属性
#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

//静态成员属于类本身，可以直接通过类名访问
//非静态成员属于对象实例，必须通过对象访问
//在类的成员函数内部，可以直接访问所有成员
//静态函数只能访问静态成员，不能访问非静态成员
//静态资源可以直接用类来引用

void setup() {  
  Serial.begin(115200);
  Serial.println("Starting BLE work!");
//创建一个名为“ MyESP32 ”的 BLE 设备,static函数是类的资源，可以直接用类来引用
  BLEDevice::init("MyESP32");
  //将 BLE 设备设置为服务器
  BLEServer *pServer = BLEDevice::createServer();
  //使用之前定义的 UUID为BLE 服务器创建服务
  BLEService *pService = pServer->createService(SERVICE_UUID);
  //创建特征并设置其属性：
  //服务与特性都有一个唯一对应的UUID，每个特性有read、write、notification等属性。
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         //设置属性
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );
//为BLE特征设置一个初始值，当客户端设备（如手机）连接到ESP32并读取这个特征时，将返回这个预设的值。
  pCharacteristic->setValue("Hello World says Neil");
  pService->start();
  // BLEAdvertising *pAdvertising = pServer->getAdvertising();  // this still is working for backward compatibility
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue
  pAdvertising->setMinPreferred(0x12);
  //开始广告，使设备可被发现
  BLEDevice::startAdvertising();
  Serial.println("Characteristic defined! Now you can read it in your phone!");
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
}